package com.lhg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.lhg.mapper.AdminMapper;
import com.lhg.pojo.entity.User;
import com.lhg.service.AdminService;
import com.lhg.utils.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, User> implements AdminService {
    @Override
    public Integer login(String loginName, String password) {
        if(Strings.isNullOrEmpty(loginName) || Strings.isNullOrEmpty(password)){
            return -1;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(User::getLoginName,loginName);
        User userEntity = this.getOne(queryWrapper);
        if(userEntity == null)
            return -1;

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if(passwordEncoder.matches(password, userEntity.getPassword())){
            return userEntity.getId();
        }

        return -1;
    }

    @Override
    public User selectUserByUserName(String username) {
        if (StringUtils.isEmpty(username)){
            return null;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.clear();
        queryWrapper.lambda().eq(User::getLoginName,username);
        return this.getOne(queryWrapper);
    }
}
